from flask import render_template, flash, redirect, url_for, request, jsonify, Response
from flask_login import login_required, current_user
from app.admin import bp
# 添加User模型导入
from app.models import User, CommandTemplate
from app import db
import subprocess
# 添加os模块导入
import os
# 添加pty和select模块用于终端功能
import pty, select, subprocess, threading, json
# 添加系统信息获取相关模块
import psutil
import GPUtil
import requests  # 新增requests依赖

@bp.route('/')
@bp.route('/index')
@login_required
def index():
    # 首页直接跳转到仪表盘
    return redirect(url_for('admin.dashboard'))

@bp.route('/dashboard')
@login_required
def dashboard():
    # 获取系统资源使用情况
    cpu_percent = psutil.cpu_percent(interval=1)
    memory = psutil.virtual_memory()
    disk = psutil.disk_usage('/')
    
    # 获取GPU信息（如果可用）
    gpu_info = []
    try:
        gpus = GPUtil.getGPUs()
        for gpu in gpus:
            gpu_info.append({
                'load': round(gpu.load * 100, 1),
                'memory_used': round(gpu.memoryUsed / 1024, 1),  # MB -> GB
                'memory_total': round(gpu.memoryTotal / 1024, 1),
                'memory_percent': round(gpu.memoryUtil * 100, 1)
            })
    except:
        # 如果没有GPU或GPUtil不可用，则保持gpu_info为空列表
        pass
    
    system_info = {
        'cpu_percent': cpu_percent,
        'memory_percent': memory.percent,
        'memory_total': round(memory.total / (1024**3), 2),  # GB
        'memory_used': round(memory.used / (1024**3), 2),    # GB
        'disk_percent': round(disk.used / disk.total * 100, 1),
        'disk_total': round(disk.total / (1024**3), 2),      # GB
        'disk_used': round(disk.used / (1024**3), 2),        # GB
        'gpu_info': gpu_info
    }
    
    return render_template('admin/dashboard.html', title='仪表盘', system_info=system_info)

# 添加用户管理路由
@bp.route('/users')
@login_required
def users():
    users = User.query.all()
    return render_template('admin/users.html', title='用户管理', users=users)

# 添加模型切换路由
@bp.route('/model_switch', methods=['GET', 'POST'])
@login_required
def model_switch():
    result = None
    
    # 获取所有命令模板
    templates = CommandTemplate.query.all()
    
    if request.method == 'POST':
        # 检查是否是添加或更新模板的请求
        if 'template_name' in request.form:
            template_name = request.form.get('template_name')
            template_description = request.form.get('template_description')
            template_command = request.form.get('template_command')
            template_id = request.form.get('template_id')
            
            if template_name and template_command:
                if template_id:  # 更新现有模板
                    template = CommandTemplate.query.get(template_id)
                    if template:
                        template.name = template_name
                        template.description = template_description
                        template.command = template_command
                        db.session.commit()
                        flash('命令模板更新成功！', 'success')
                    else:
                        flash('未找到要更新的模板！', 'error')
                else:  # 添加新模板
                    template = CommandTemplate(
                        name=template_name,
                        description=template_description,
                        command=template_command
                    )
                    db.session.add(template)
                    db.session.commit()
                    flash('命令模板添加成功！', 'success')
            else:
                flash('模板名称和命令不能为空！', 'error')
                
            return redirect(url_for('admin.model_switch'))
            
        # 检查是否是执行命令的请求
        elif 'execute_template' in request.form:
            # 执行指定模板命令
            template_id = request.form.get('execute_template')
            template = CommandTemplate.query.get(template_id)
            
            if template:
                try:
                    # 修改为在用户主目录执行命令
                    result = subprocess.check_output(
                        template.command, 
                        shell=True, 
                        stderr=subprocess.STDOUT, 
                        text=True,
                        cwd=os.path.expanduser('~')
                    )
                except subprocess.CalledProcessError as e:
                    result = f"命令执行失败: {e.output}"
                except Exception as e:
                    result = f"发生错误: {str(e)}"
            else:
                result = "未找到指定的命令模板"
        
        # 检查是否是删除模板的请求
        elif 'delete_template' in request.form:
            template_id = request.form.get('delete_template')
            template = CommandTemplate.query.get(template_id)
            
            if template:
                db.session.delete(template)
                db.session.commit()
                flash('命令模板删除成功！', 'success')
            else:
                flash('未找到要删除的模板！', 'error')
            
            return redirect(url_for('admin.model_switch'))
        
        # 删除自定义命令执行功能，移除此else分支
    
    templates = CommandTemplate.query.all()
    return render_template('admin/model_switch.html', title='模型切换', result=result, templates=templates)

# 添加终端路由
@bp.route('/terminal')
@login_required
def terminal():
    return render_template('admin/terminal.html', title='终端')

# 添加终端执行命令的API端点
@bp.route('/terminal_execute', methods=['POST'])
@login_required
def terminal_execute():
    data = request.get_json()
    command = data.get('command')
    
    if not command:
        return jsonify({'error': '命令不能为空'}), 400
    
    try:
        # 在用户主目录执行命令
        result = subprocess.check_output(
            command, 
            shell=True, 
            stderr=subprocess.STDOUT, 
            text=True,
            cwd=os.path.expanduser('~')
        )
        return jsonify({'output': result})
    except subprocess.CalledProcessError as e:
        return jsonify({'output': f"命令执行失败: {e.output}"})
    except Exception as e:
        return jsonify({'output': f"发生错误: {str(e)}"})

# 添加模型状态检测接口
@bp.route('/model_status')
@login_required
def model_status():
    try:
        output = subprocess.check_output(
            "curl --max-time 5 localhost:8080",
            shell=True,
            stderr=subprocess.STDOUT,
            text=True
        )
        # 若curl执行成功但内容为空，也返回200
        if not output.strip():
            output = "服务已响应 (内容为空)"
        return Response(output, mimetype='text/plain')
    except subprocess.CalledProcessError as e:
        # curl执行失败时返回错误内容
        err_output = e.output or "curl 执行失败"
        return Response(err_output, mimetype='text/plain', status=500)
    except Exception as e:
        return Response(str(e), mimetype='text/plain', status=500)

@bp.route('/current_model')
@login_required
def current_model():
    try:
        response = requests.get("http://localhost:8080/v1/models", timeout=5)
        response.raise_for_status()
        data = response.json()
        model_name = data.get("data", [{}])[0].get("id", "未知模型")
        return jsonify({'model_name': model_name})
    except requests.RequestException as e:
        return jsonify({'error': f"无法获取模型名称: {str(e)}"}), 500
    except (KeyError, IndexError):
        return jsonify({'error': "返回数据格式错误"}), 500

@bp.route('/model_chat')
@login_required
def model_chat():
    return render_template('admin/model_chat.html', title='模型测试')

@bp.route('/model_chat_api', methods=['POST'])
@login_required
def model_chat_api():
    data = request.get_json()
    message = data.get('message')
    
    if not message:
        return jsonify({'error': '消息内容不能为空'}), 400
    
    try:
        response = requests.post(
            "http://localhost:8080/v1/chat",
            json={"message": message},
            timeout=5
        )
        response.raise_for_status()
        reply = response.json().get('reply', '模型未返回任何内容')
        return jsonify({'reply': reply})
    except requests.RequestException as e:
        return jsonify({'error': f"请求失败: {str(e)}"}), 500

# 添加性能测试页面路由
@bp.route('/performance_test')
@login_required
def performance_test():
    return render_template('admin/performance_test.html', title='性能测试')

@bp.route('/performance')
@login_required
def performance():
    return render_template('admin/performance.html', title='性能测试')
